package com.smartResponse;

import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.os.Bundle;
import android.content.*;
import android.database.Cursor;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;


//We need to develop a way to make sure that the same name can not be entered twice.



public class EditMessage extends Activity {
    EventDB db = new EventDB(this);
    String bundle_m_name;
    String bundle_l_name;
    long id;
	
		@Override
		@SuppressWarnings("unchecked")
		public void onCreate(Bundle savedInstanceState) {
		    super.onCreate(savedInstanceState);
		    setContentView(R.layout.editmessagelayout);
		    Bundle extras = getIntent().getExtras(); 
		    if(extras !=null)
		    {
		    bundle_m_name = extras.getString("message");
		    bundle_l_name = extras.getString("location");
		    }
		    else{
		    	bundle_m_name = "";
		    	bundle_l_name  = "";
		    }
		    EditText name = (EditText) findViewById(R.id.m_name);
		    EditText message= (EditText) findViewById(R.id.m_message);
		    EditText frequency = (EditText) findViewById(R.id.m_freq);

		    db.open();
	        Cursor c = db.getAllMessages();
			//finds the record in the database from a location name
	        while (c.moveToNext())
	        {
	            String results = c.getString(1); 

				if(results.equals(bundle_m_name))
				{
				id = c.getLong(0);
				}
	        }
	        //end lookup
	         Cursor c2 = db.getAllMessages();
	        while (c2.moveToNext())
	        {
	            long results = c2.getLong(0); 

				if(results == id)
				{
				name.setText(c2.getString(1));
		        message.setText(c2.getString(2));
		        frequency.setText(c2.getString(3));
		        bundle_l_name = c2.getString(5);
				}
	        }
	        //end lookup
	        db.close();
		    Spinner location_name = (Spinner) findViewById(R.id.locations);
		    @SuppressWarnings("rawtypes")
			ArrayAdapter locations_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
		    locations_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		    
		    locations_adapter.add("None");

		    db.open();
	        Cursor cursor = db.getAllLocations();
	        while (cursor.moveToNext())
	        {
	            String location = cursor.getString(1);
	            locations_adapter.add(location);
	        }
	        db.close();
	        location_name.setAdapter(locations_adapter);
        	
		    db.open();
		    int j = 1;
	        Cursor cursor2 = db.getAllLocations();
	        while (cursor2.moveToNext())
	        {
	            String location = cursor2.getString(1);
		        if (location.equals(bundle_l_name)){
		        	location_name.setSelection(j);
				} else {
					j = j + 1;
				}

	        }
	        db.close();

	        on_OK_Button_Click();
	        on_Cancel_Button_Click();
}

		public void on_OK_Button_Click() {
			
			Button Button = (Button) findViewById(R.id.m_ok);
			Button.setOnClickListener(new OnClickListener() {
	 
				public void onClick(View v) {
					//The code below stores the text in the box to a string
				    EditText name = (EditText) findViewById(R.id.m_name);
				    EditText message= (EditText) findViewById(R.id.m_message);
				    EditText freq = (EditText) findViewById(R.id.m_freq);
				    Spinner location_name = (Spinner) findViewById(R.id.locations);
				    
		        	String et_name = name.getText().toString();
					String et_message = message.getText().toString();
					String et_frequency = freq.getText().toString();
		        	String et_l_name = location_name.getSelectedItem().toString();
	        		db.open();
			        Cursor c = db.getAllMessages();
						//finds the record in the database from a message name
			            String db_name = "";
			            String db_message = "";
			            String db_freq = "";
			            String db_l_name = "";
				        while (c.moveToNext())
				        {
				            long results = c.getLong(0); 

							if(results == id)
							{
							db_name=c.getString(1);
							db_message=c.getString(2);
							db_freq=c.getString(3);
							db_l_name=c.getString(5);
							}
				        }
				        //end lookup
				        db.close();
				        //The if statements below check for change in location record data
				       	if (db_name.equals(et_name)){
				        	}
				        		else{
					        		et_name.equals(db_name);
				        		}
				        	if (db_message.equals(et_message)){
				        	}
				        		else{
				        			et_message.equals(db_message);
				        	}
				        	if (db_freq.equals(et_frequency)){
				        	}
				        		else{
				        			et_frequency.equals(db_freq);
				        	}
				        	if (db_l_name.equals(et_l_name)){
				        	}
				        		else{
				        			et_l_name.equals(db_l_name);
				        	}
						    boolean name_is_valid = true;
						    boolean location_used = true;
						    boolean frequency_valid = true;
						    boolean valid_message = true;
						    db.open();
					        Cursor c1 = db.getAllMessages();
					        while (c1.moveToNext()){
					            String results = c1.getString(1);
					            if (results.equals(et_name)){ 	
					            	 name_is_valid=false;
					            }
					        }
					        if  (et_name == null || et_name.isEmpty()){
					        	name_is_valid = false;
					        }
					        if (et_name.equals(bundle_m_name)){
					        	name_is_valid = true;
					        }
					        db.close();
					        if (name_is_valid == true){	
					            Spinner mySpinner = (Spinner)findViewById(R.id.locations);
					            String l_name = mySpinner.getSelectedItem().toString();	
					            //checks if the location is in use
							    db.open();
						        Cursor c2 = db.getAllMessages();
						        while (c2.moveToNext()){
						            String loc = c2.getString(5);
						            if (loc.equals(l_name)){
						            	if (l_name != "None"){
						            		location_used = false;				            		
						            	}

						            	}
						        }
						        db.close();
						        if (et_l_name.equals(bundle_l_name)){
						        	location_used = true;
						        }
						        //checks if frequency is valid
					        	if (et_frequency == null || et_frequency.isEmpty()) {
					        		frequency_valid = false;
					        		} else {
					        		   try {
					        		     @SuppressWarnings("unused")
										double num = Double.parseDouble(et_frequency);
					        		   }
					        		   catch (NumberFormatException e) {
					        			   frequency_valid = false;
					        		   }
					        		}
					        		
						        if (location_used == true){	
						        	if (frequency_valid == true){
							        	if (et_message.isEmpty()) {
							        		frequency_valid = false;
							        		}
						        		if (valid_message == true){
								            updateMessage(id, et_name, et_message,et_frequency, et_l_name);
								        	ViewMessage.change_name(et_name,true); 
									        Intent in = new Intent();
									        setResult(1,in);//Here I am Setting the Requestcode 1, you can put according to your requirement
									        finish();
						        		}
						        		if (valid_message == false){
								        	Context context = getApplicationContext();
								        	CharSequence text = "Please enter a valid message and try again.";
								        	int duration = Toast.LENGTH_LONG;
								        	Toast toast = Toast.makeText(context, text, duration);
								        	toast.show();			
						        		}
										
						        	}
						        	if (frequency_valid == false){
							        	Context context = getApplicationContext();
							        	CharSequence text = "Please enter a time, in seconds, that you would like to wait before sending a reponse between recieved messages.";
							        	int duration = Toast.LENGTH_LONG;
							        	Toast toast = Toast.makeText(context, text, duration);
							        	toast.show();				        	
							        }

						        }
						        if (location_used == false){	
						        	Context context = getApplicationContext();
						        	CharSequence text = "There is already a message event associated with the selected location."+ "\n\n" +
						        	"Please edit the message event associated with this location, or change the location.";
						        	int duration = Toast.LENGTH_LONG;
						        	Toast toast = Toast.makeText(context, text, duration);
						        	toast.show();
						        }
					        }
					        if (name_is_valid == false){	
					        	Context context = getApplicationContext();
					        	CharSequence text = "That message name is already in use or is invalid, please enter a different name";
					        	int duration = Toast.LENGTH_LONG;
					        	Toast toast = Toast.makeText(context, text, duration);
					        	toast.show();
					        }
			        }
				

			} );
	}
		public void on_Cancel_Button_Click() {
			 
			Button Button = (Button) findViewById(R.id.m_cancel);
	 
			Button.setOnClickListener(new OnClickListener() {
	 
				public void onClick(View v) {
			        Intent in = new Intent();
			        setResult(RESULT_CANCELED,in);//Here I am Setting the Requestcode to 0, This will not update the activity
			        finish();
				}

			} );
	}

	    public void updateMessage(long id, String name, String message, String freq, String l_name)
	    {
	    	EventDB db = new EventDB(this);
	        db.open();        
	        db.updateMessage(
	        		id,
	        		name,
	        		message,
	        		freq,
	        		"Null",
	        		l_name);      
	        db.close();
	    	
	    } 
		//The code in the function below checks to see if a new location was added and if so it refreshes the page
	    @Override
	    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	        super.onActivityResult(requestCode, resultCode, data);
	        
	        if(resultCode==1){
	        	Intent refresh = new Intent(EditMessage.this, EditMessage.class);
			    refresh.putExtra("message", getIntent().getExtras().getString("message"));
	            this.finish();
	            startActivity(refresh);

	        }
	        if(resultCode==RESULT_CANCELED){
	            Intent refresh = new Intent(EditMessage.this, EditMessage.class);
	            startActivity(refresh);
	            this.finish();
	        }
	        
	    }
		//This code controls what happens when the back key is pressed
		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event)  {
		    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
		    	on_Cancel_Button_Click();
		    }

		    return super.onKeyDown(keyCode, event);
		}
		//Menu Layout
		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			super.onCreateOptionsMenu(menu);
			menu.add(0,1,0,"Home").setIcon(R.drawable.home);
	        menu.add(0,2,0,"OK").setIcon(R.drawable.add_icon);
	        menu.add(0,3,0,"Cancel").setIcon(R.drawable.cancel);
		    return true;
		}
	    @Override
	     public boolean onOptionsItemSelected(MenuItem item) {
	        switch (item.getItemId()) {
	        case 1:
			  Intent home_intent_menu = new Intent(EditMessage.this, MainActivity.class);
			  startActivity(home_intent_menu);
			  return true;
	        case 2:
	        	on_OK_Button_Click();
	        	return true;
	     case 3:
	    	 	on_Cancel_Button_Click();
	            return true;
	          }
			return false;
	    }
}